#coding=utf-8
from app.models import*

#设置自动请求
def spider_following_requests(json_data):
    if json_data['auto_switch'] == 'enable':
        tmp = SpiderWork(json_data['user_appkey'],
                        json_data['cat_id'],
                        'enable',
                        '',
                        '',
                        '',
                        0,
                        0
                        )
        db.session.add(tmp)
        db.session.commit() 
    elif json_data['auto_switch'] == 'disable':
        user_appkey_res = SpiderWork.query.filter(SpiderWork.user_appkey == json_data['user_appkey'])
        current_res = user_appkey_res.first()
        current_res.user_auto_catgory = 'disable'
        db.session.commit()

#设置点击后的店铺列表
def spider_itemfollowing_requests(json_data):
    user_appkey_res = SpiderWork.query.filter(SpiderWork.user_appkey == json_data['user_appkey'])
    if user_appkey_res.count() == 0:
        return
    str_url = json_data['item_url']
    current_res = user_appkey_res.first()
    num_item = current_res.user_item_num
    list_work = []
    list_work.extend(current_res.user_item_work1.split("||"))  # || 
    list_work.extend(current_res.user_item_work2.split("||"))
    list_work.extend(current_res.user_item_work3.split("||"))
    list_work = [x for x in list_work if x != '']
    if num_item < 30 and str_url not in list_work:
        list_work.append(str_url)
        list_total = [list_work[i:i+10] for i in range(0, len(list_work), 10)]
        #print('list_work',list_work)
        #print('list_total',list_total)
        for num in range(len(list_total)):
            if num == 0:
                current_res.user_item_work1 = "||".join(list_total[num])
            if num == 1:
                current_res.user_item_work2 = "||".join(list_total[num])
            if num == 2:
                current_res.user_item_work2 = "||".join(list_total[num])
        current_res.user_item_num += 1
    if num_item == 30:
        list_work = list_work[1:] + list_work[:1]
        list_work[-1] = str_url
        list_total = [list_work[i:i+10] for i in range(0, len(list_work), 10)]
        for num in range(len(list_total)):
            current_res.user_item_work1 = "||".join(list_total[num])

    db.session.commit()